using System.Collections;
using Game.Core;
using Game.Main.Controller;
using Game.Manager;
using UnityEngine;

namespace Game.Main.View
{
	public class LoadingView : BaseView
	{
		private SceneController clr;

		private GameObject btnStart;

		private CanvasGroup canvasGroup;

		private Transform iconTrans;

		private CanvasGroup iconCanvas;

		private float timer;

		private bool isAppear;

		private bool isClosing;

		private float canvasAlpha = 1f;

		private float iconAlpha = 1f;

		private float appearSpeed;

		public LoadingView(SceneController clr)
			: base("prefabs/ui/scene/loadingview", Singleton<UIManager>.Instance.uiLayer)
		{
			viewName = "LoadingView";
			this.clr = clr;
		}

		protected override void OnLoaded()
		{
			canvasGroup = transform.GetComponent<CanvasGroup>();
			canvasGroup.alpha = canvasAlpha;
			iconTrans = GetChild("Icon");
			iconCanvas = iconTrans.GetComponent<CanvasGroup>();
			int childCount = iconTrans.childCount;
			RandomIcon();
			Client.Instance.StartCoroutine(MainLoop());
		}

		private void RandomIcon()
		{
			if (iconTrans == null)
			{
				return;
			}
			int childCount = iconTrans.childCount;
			int num = Random.Range(0, childCount);
			for (int i = 0; i < childCount; i++)
			{
				if (i == num)
				{
					iconTrans.GetChild(i).gameObject.SetActive(true);
				}
				else
				{
					iconTrans.GetChild(i).gameObject.SetActive(false);
				}
			}
		}

		public void IsAppear(bool val, float speed)
		{
			isAppear = val;
			if (isAppear)
			{
				canvasAlpha = 0f;
				appearSpeed = speed;
				RandomIcon();
			}
			else
			{
				canvasAlpha = 1f;
			}
			if (canvasGroup != null)
			{
				canvasGroup.alpha = canvasAlpha;
			}
		}

		public IEnumerator MainLoop()
		{
			while (transform != null)
			{
				if (isAppear)
				{
					canvasAlpha += Time.deltaTime * appearSpeed;
					canvasGroup.alpha = canvasAlpha;
					if (canvasAlpha >= 1f)
					{
						canvasAlpha = 1f;
						isAppear = false;
						Fire(new BaseEvent("game.loading_view_appear"));
					}
				}
				else if (isClosing)
				{
					if (iconAlpha > 0f)
					{
                        iconAlpha -= Time.deltaTime * 2f;
						iconCanvas.alpha = iconAlpha;
					}
					if (iconAlpha < 0.4f)
					{
						canvasAlpha -= Time.deltaTime * 2f;
						canvasGroup.alpha = canvasAlpha;
						if (canvasAlpha <= 0f)
						{
							clr.DestroyLoadingView();
						}
					}
				}
				yield return new WaitForEndOfFrame();
			}
		}

		public void CloseView()
		{
			isClosing = true;
		}
	}
}
